//
//  GroupManagerVC.swift
//  YueChat
//
//  Created by 1 on 2024/10/29.
//

import UIKit

class GroupManagerVC: BaseVC {
    
    var group = DMCCGroup()
    var addGroupArray : Array<Any> = []

    override func viewDidLoad() {
        super.viewDidLoad()

        title = "群管理"
        setup()
        
        NotificationCenter.default.addObserver(self, selector: #selector(onGroupRefreshChanged), name: NSNotification.Name(rawValue: kGroupUpdateChanged), object: nil)
    }
    
    @objc func onGroupRefreshChanged () {
        guard let groupInfo = gosnGroup.getGroupInfo(group.groupId) else {
            return
        }
        self.group = groupInfo
        self.tableView.reloadData()
    }
    
    init(group: DMCCGroup = DMCCGroup()) {
        super.init(nibName: nil, bundle: nil)
        self.group = group
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    func setup () {
        dataSource = [["管理员","设置禁言"],["加群方式","设置进群密码"],["提示群人数"]]
//        dataSource = [["管理员","设置禁言"],["提示群人数"]]
        addGroupArray = ["自由进群","群成员可以邀请","只能群管理邀请","进群需要申请","输入密码进群"]
        tableView.dataSource = self
        tableView.delegate = self

        tableView.register(UINib(nibName: "SubTitleCell", bundle: nil), forCellReuseIdentifier: "SubTitleCell")
    }
    

  
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 1 && indexPath.row == 1 {
            if group.joinType == .password {
                return 60
            }else{
                return 0
            }
        }
        return 60
    }
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataSource.count
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        let array = dataSource[section] as! Array<String>
        return array.count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 0.01
    }
    
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//        let view = UIView(frame: CGRect(x: 0, y: 0, width: kScreenWidth, height: 10))
//        view.backgroundColor = UIColor.lightGray
//        return view
//    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            
        let array = self.dataSource[indexPath.section] as! Array<String>
        let name = array[indexPath.row]
        if indexPath.section == 0 {
            let cell = UITableViewCell(style: .default, reuseIdentifier: "cell")
            cell.contentView.backgroundColor = UIColor.clear
            cell.accessoryType = .disclosureIndicator
            cell.textLabel?.text = name
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "SubTitleCell", for: indexPath) as! SubTitleCell
        cell.titleLab.text = name
        cell.subTitleLab.font = UIFont.systemFont(ofSize: 15)
        cell.subTitleLab.textColor = UIColor.gray
        cell.accessoryType = .disclosureIndicator
        if indexPath.section == 1 {
            let join = group.joinType
            if indexPath.row == 0 {
                
                cell.subTitleLab.text = (addGroupArray[getJoinType(join.rawValue)] as! String)
            }else{
                cell.accessoryType = .none
                cell.subTitleLab.text = ""
            }
                
        }else {
            cell.subTitleLab.text = "当前群上限\(group.maxMemberCount)人"
        }
        
        return cell
    }
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

        tableView.deselectRow(at: indexPath, animated: true)
        let array = self.dataSource[indexPath.section] as! Array<String>
        let name = array[indexPath.row]
        
        if name == "提示群人数" {
            presentVC(VC: UpdateGroupVC(group: group))
        }else if name == "管理员" {
            navigationController?.pushViewController(ManagerListVC(group: group), animated: true)
        }else if name == "设置禁言" {
            navigationController?.pushViewController(GroupMuteVC(group: group), animated: true)
        }else if name == "加群方式" {
            showJoinType()
        }else if name == "设置进群密码" {
            setPassword()
        }
        
    }
    
    func showJoinType() {
        let alertController = UIAlertController(title: "设置加群方式", message: "", preferredStyle: .actionSheet)

        let cancelAction = UIAlertAction(title: KLocalizedString("Cancel"), style: .cancel) { _ in
            // 取消操作
        }

        let action1 = UIAlertAction(title: (addGroupArray[0] as! String), style: .default) { [weak self] _ in
            guard let self = self else {return}
            if self.group.joinType != .free {
                self.group.joinType = .free
                self.changeJoinType()
                self.tableView.reloadData()
            }
        }
        
        let action2 = UIAlertAction(title: (addGroupArray[1] as! String), style: .default) { [weak self] _ in
            guard let self = self else {return}
            if self.group.joinType != .member {
                self.group.joinType = .member
                self.changeJoinType()
                self.tableView.reloadData()
            }
        }
        
        let action3 = UIAlertAction(title: (addGroupArray[2] as! String), style: .default) { [weak self] _ in
            guard let self = self else {return}
            if self.group.joinType != .admin {
                self.group.joinType = .admin
                self.changeJoinType()
                self.tableView.reloadData()
            }
        }
        
        let action4 = UIAlertAction(title: (addGroupArray[3] as! String), style: .default) { [weak self] _ in
            guard let self = self else {return}
            if self.group.joinType != .verify {
                self.group.joinType = .verify
                self.changeJoinType()
                self.tableView.reloadData()
            }
        }
        
        let action5 = UIAlertAction(title: (addGroupArray[4] as! String), style: .default) { [weak self] _ in
            guard let self = self else {return}
            if self.group.joinType != .password {
                self.group.joinType = .password
                self.changeJoinType()
                self.tableView.reloadData()
            }
        }



        alertController.addAction(action1)
        alertController.addAction(action2)
        alertController.addAction(action3)
        alertController.addAction(action4)
        alertController.addAction(action5)
        alertController.addAction(cancelAction)

        if let popoverController = alertController.popoverPresentationController {
            popoverController.permittedArrowDirections = []
            popoverController.sourceView = self.view
            popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
        }

        present(alertController, animated: true, completion: nil)
    }
    
    func changeJoinType () {
        Task {
            let res = await gosnGroup.setJoinType(group.groupId, group.joinType)
            if res {
                
            }
        }
    }
    
    func setPassword() {
        let title = "设置进群密码"
        let topVC = UIApplication.shared.keyWindow?.rootViewController ?? UIViewController()
        let presentedVC = topVC.presentedViewController
        let vc = presentedVC ?? topVC

        let alert = UIAlertController(title: title, message: "", preferredStyle: .alert)
        let okAction = UIAlertAction(title: KLocalizedString("Sure"), style: .default) { [self] _ in
            guard let inputText = alert.textFields?.first?.text, inputText.count <= 12 else {
                MHAlert.showMessage(KLocalizedString("输入不能为空"))
                return
            }

            Task {
                let res = await gosnGroup.setJoinPassword(osnId: group.groupId, password: inputText)
                
                await MainActor.run {
                    if res{
                        MHAlert.showMessage(KLocalizedString("设置成功"))

                    }else{
                        MHAlert.showMessage(KLocalizedString("设置失败"))
                    }
                }
                
            }
            
        }

        let cancelAction = UIAlertAction(title: KLocalizedString("Cancel"), style: .default, handler: nil)

        alert.addTextField { [self] textField in
//            textField.placeholder = KLocalizedString("ModifyGroupName")
//            textField.text = group.name
            textField.clearButtonMode = .always
        }

        alert.addAction(cancelAction)
        alert.addAction(okAction)
        vc.present(alert, animated: true, completion: nil)
    }
    func getJoinType(_ str:String) -> Int {
        switch str {
        case "free":
            return 0
        case "member":
            return 1
        case "admin":
            return 2
        case "verify":
            return 3
        case "password":
            return 4
        default:
            return 0
        }
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: kGroupUpdateChanged), object: nil)
    }

}
